package com.hdu.webServer.multi;

import com.hdu.utils.ByteBufferUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class Server {


    private static final List<Worker> workers = new ArrayList<>();
    private static final AtomicInteger workerIndex = new AtomicInteger();

    static {
        int processors = Runtime.getRuntime().availableProcessors();
        for (int i = 0; i < processors; i++) {
            workers.add(new Worker("worker-" + i));
        }
    }

    public static void main(String[] args) throws IOException {
        Thread.currentThread().setName("boss");

        Selector selector = Selector.open();

        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.bind(new InetSocketAddress(8080));
        ssc.configureBlocking(false);
        SelectionKey sscKey = ssc.register(selector, 0, null);
        sscKey.interestOps(SelectionKey.OP_ACCEPT);

        while (true) {
            selector.select();
            Iterator<SelectionKey> readyKeys = selector.selectedKeys().iterator();
            while (readyKeys.hasNext()) {
                SelectionKey readyKey = readyKeys.next();
                readyKeys.remove();
                if (readyKey.isAcceptable()) {
                    log.info("handle accept");
                    SocketChannel sc = ssc.accept();
                    sc.configureBlocking(false);
                    workers.get(workerIndex.getAndIncrement() % workers.size()).register(sc);
                }
            }
        }
    }

    static class Worker implements Runnable {

        private Selector selector;
        private final String name;

        private final static int STOP = 0;
        private final static int RUNNING = 1;
        private final AtomicInteger STATE = new AtomicInteger(STOP);
        private final ConcurrentLinkedDeque<Runnable> registerQueue = new ConcurrentLinkedDeque<>();

        private Worker(String name) {
            this.name = name;
        }

        /**
         * 初始化线程和 selector
         *
         * @throws IOException
         */
        public void register(SocketChannel sc) throws IOException {

            if (STATE.compareAndSet(STOP, RUNNING)) {
                Thread thread = new Thread(this, name);
                selector = Selector.open();
                thread.start();
            }

            registerQueue.add(() -> {
                try {
                    sc.register(selector, SelectionKey.OP_READ, null);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });

            selector.wakeup();
        }


        @Override
        public void run() {
            handleRead();
        }

        @SuppressWarnings("all")
        void handleRead() {
            while (true) {
                try {
                    selector.select();
                    Runnable registerTask = registerQueue.poll();
                    if (registerTask != null) {
                        registerTask.run();
                    }
                    Iterator<SelectionKey> readyKeys = selector.selectedKeys().iterator();
                    while (readyKeys.hasNext()) {
                        SelectionKey readyKey = readyKeys.next();
                        readyKeys.remove();
                        if (readyKey.isReadable()) {
                            log.info("handle read");
                            ByteBuffer buffer = ByteBuffer.allocate(16);
                            SocketChannel channel = ((SocketChannel) readyKey.channel());
                            channel.read(buffer);
                            buffer.flip();
                            ByteBufferUtil.debugAll(buffer);
                        }
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}


